import Objects from "../../utils/objects";

function CartesianChooser(viewer) {
    this._viewer = viewer;
    this.handler = new Cesium.ScreenSpaceEventHandler(this._viewer.scene.canvas);
}

CartesianChooser.prototype.start = function(callback, error) {
    let that = this;
    this.handler.setInputAction(evt => {
        // choose point
        let cartesian3 = that._getCartesian3FromPosition(evt.position, []);
        if (Objects.isNull(cartesian3)) {
            error && error();
        }

        callback && callback(cartesian3);

        this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

CartesianChooser.prototype._getCartesian3FromPosition = function(position, ...noPickEntityArray) {
    let that = this;

    let picks = this._viewer.scene.drillPick(position);
    this._viewer.render();

    let getOnModel = false;
    let cartesian3 = null;

    if (this._viewer.scene.pickPositionSupported) {
        for (let i = 0; i < picks.length; i++) {
            let pickedObject = picks[i];
            for (let j = 0; j < noPickEntityArray.length; j++) {
                let noPickEntity = noPickEntityArray[j];
                if (that._hasPickedModel(pickedObject, noPickEntity)) {
                    getOnModel = true;
                }
            }
        }
    }

    if (getOnModel) {
        cartesian3 = this._viewer.scene.pickPosition(position);
    } else {
        let ray = this._viewer.camera.getPickRay(position);
        if (Objects.isNull(ray)) {
            return null;
        }
        cartesian3 = this._viewer.scene.globe.pick(ray, this._viewer.scene);
    }
    return cartesian3;
};

export default CartesianChooser;
